
import { getShopCartAsyn } from '@/api/asyn'
import { toast } from '@/utils/extendApi'
Page({
  data: {
    title: "商品推荐",
    goodsData: [],
    shopCartData: [],
    goodsS: {
      page: 1,
      size: 10,
      total: 0
    },
    orderInfo: {
      price: 0,
      goods: [],
      discountPrice: 0,
      type: 'ORDINARY',
      orderSource: 'PAY'
    },
    allCheck: false
  },

  onLoad() {
    this.getAllData()
  },
  async getAllData() {
    const res = await getShopCartAsyn(this.data.goodsS);
    const data = res[1].data.map(s => {
      return { ...s, checked: false }
    })
    this.setData({
      goodsData: res[0].data.records,
      shopCartData: data
    })
  },
  radio(event: any) {
    const data = this.data.shopCartData.map(s => {
      if (s.id === event.currentTarget.dataset.id) {
        s.checked = !s.checked
      }
      return s
    })
    let allGoodsIds = [] as String[]
    const totalPrice = data.reduce((sumData, key) => {
      if (key.checked) {
        allGoodsIds.push(key)
        return sumData + key.price * key.goodsNum
      }
      return sumData
    }, 0)

    this.setData({
      shopCartData: data,
      "orderInfo.goods": allGoodsIds,
      "orderInfo.price": totalPrice * 100,
    })
  },
  onNumChange(event: any) {
    let msg = ""
    const data = this.data.shopCartData.map(s => {
      if (s.id === event.currentTarget.dataset.id) {
        if (s.goodsTotalNum < event.detail) {
          s.goodsNum = s.goodsTotalNum
          msg = "超出库存数量！"
        } else {
          s.goodsNum = event.detail
        }
      }
      return s
    })
    const totalPrice = data.reduce((sumData, key) => {
      if (key.checked) {
        return sumData + key.price * key.goodsNum
      }
      return sumData
    }, 0)
    this.setData({
      shopCartData: data,
      "orderInfo.price": totalPrice * 100
    })
    if (msg !== '') {
      toast({ title: msg })
      return
    }
  },
  allCheck() {
    const data = this.data.shopCartData.map(s => {
      s.checked = !this.data.allCheck
      return s
    })
    let allGoodsIds = [] as String[]
    const totalPrice = data.reduce((sumData, key) => {
      if (key.checked) {
        allGoodsIds.push(key)
        return sumData + key.price * key.goodsNum
      }
      return sumData
    }, 0)
    this.setData({
      shopCartData: data,
      allCheck: !this.data.allCheck,
      "orderInfo.goods": allGoodsIds,
      "orderInfo.price": totalPrice * 100
    })
  }
})
